"""
@description: 日志记录
@time 2023/09/06 15:09:09
"""

import logging
import os
from logging.handlers import RotatingFileHandler


def setup_logger():
    """
    创建日志记录器
    """
    root_path = os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    )
    log_base_path = os.path.join(root_path, "logs")
    os.makedirs(log_base_path, exist_ok=True)

    # 通用日志格式
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )

    # 创建根 logger
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)

    # 定义日志子目录及对应的 logger 名称
    log_configs = [
        {"name": "app", "subdir": "app", "level": logging.DEBUG},
        {"name": "login", "subdir": "login", "level": logging.INFO},
        {"name": "action", "subdir": "action", "level": logging.INFO},
        {"name": "code_batch", "subdir": "code_batch", "level": logging.INFO},
        # 可以继续添加更多日志分类
    ]

    for config in log_configs:
        logger_name = config["name"]
        subdir = config["subdir"]
        log_level = config["level"]

        # 创建子目录路径
        log_dir = os.path.join(log_base_path, subdir)
        os.makedirs(log_dir, exist_ok=True)

        # 构建日志文件路径
        log_file = os.path.join(log_dir, f"{logger_name}.log")

        # 创建 handler
        handler = RotatingFileHandler(
            log_file, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8"
        )
        handler.setLevel(log_level)
        handler.setFormatter(formatter)

        # 获取并配置 logger
        logger = logging.getLogger(logger_name)
        logger.setLevel(log_level)
        logger.addHandler(handler)
        logger.propagate = False  # 不传播给 root logger

    # 如果你想让 root logger 输出到主日志文件，也可以单独设置
    root_handler = RotatingFileHandler(
        os.path.join(log_base_path, "app", "app.log"),
        maxBytes=5 * 1024 * 1024,
        backupCount=3,
        encoding="utf-8",
    )
    root_handler.setLevel(logging.DEBUG)
    root_handler.setFormatter(formatter)
    root_logger.addHandler(root_handler)

    root_logger.info("Logger initialized with subdirectories.")

    # 配置sqlachemy
    logging.getLogger("databases").setLevel(logging.WARNING)
    return root_logger
